import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import tailwindcss from '@tailwindcss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import viteCompression from 'vite-plugin-compression'
import type { MinifyOptions } from 'terser'


export default defineConfig(({ command, mode }) => {
  const isProd = mode === 'production'
  const terserOptions: MinifyOptions = {
    compress: {
      drop_console: true,
      drop_debugger: true,
      pure_funcs: ['console.log'], // 移除 console.log
      dead_code: true, // 移除死代码
      loops: true, // 优化循环
    },
    mangle: {
      safari10: true, // 兼容 Safari 10
    },
  }

  return {
    plugins: [
      vue({
        // 新增：模板编译选项优化
        template: {
          compilerOptions: {
            // 生产环境移除 whitespace
            whitespace: isProd ? 'condense' : 'preserve',
          },
        },
      }),
      tailwindcss(),
      AutoImport({
        imports: ['vue', 'vue-router', 'pinia'],
        dts: 'src/auto-imports.d.ts',
        eslintrc: { 
          enabled: true, 
          filepath: './.eslintrc-auto-import.json' 
        },
      }),
      // 只在开发环境启用 vue-devtools
      command === 'serve' && vueDevTools(),
      // gzip 压缩 (兼容性更好)
      isProd && viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz',
      }),
      // Brotli 压缩 (压缩率更好)
      // isProd && viteCompression({
      //   algorithm: 'brotliCompress',
      //   ext: '.br',
      //   threshold: 10240,
      // }),
    ].filter(Boolean),
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    optimizeDeps: {
      exclude: ['element-plus/theme-chalk'],
      // 预构建优化
      include: [
        'vue',
        'vue-router',
        'pinia',
        // 添加其他常用但可能未被检测到的依赖
      ],
    },
    build: {
      target: 'es2015',
      sourcemap: false,
      minify: 'terser',
      terserOptions,
      // 新增：构建产物优化
      reportCompressedSize: false, // 关闭 gzip 大小报告
      chunkSizeWarningLimit: 1500, // 提高 chunk 大小警告阈值
      // 新增：资产优化
      assetsInlineLimit: 4096, // 4kb 以下资源转 base64
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              if (id.includes('vue-router')) return 'vendor_router'
              if (id.includes('pinia')) return 'vendor_pinia'
              if (id.includes('element-plus')) return 'vendor_element'
              if (id.includes('vue')) return 'vendor_vue'
              return 'vendor_others'
            }

            if (id.includes('src/views/') || id.includes('src/pages/')) {
              const match = id.match(/src\/views\/([^\/]+)/) || id.match(/src\/pages\/([^\/]+)/)
              if (match && match[1]) return `page_${match[1].toLowerCase()}`
            }

            if (id.includes('src/utils/') || id.includes('src/composables/')) {
              return 'chunk_utils'
            }
          },
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: (assetInfo) => {
            // 细化资源分类
             const extType = assetInfo.name?.split('.')[1]
                if (extType && /png|jpe?g|svg|gif|tiff|bmp|ico/i.test(extType)) {
                  return 'assets/images/[name]-[hash][extname]'
                }
                if (extType && /woff|woff2|eot|ttf|otf/i.test(extType)) {
                  return 'assets/fonts/[name]-[hash][extname]'
                }
                return 'assets/[ext]/[name]-[hash].[ext]'
          },
        },
      },
    },
    server: {
      host: '0.0.0.0',
      port: 3000,
      open: true, // 自动打开浏览器
      cors: true,
      // 代理配置（根据实际需求添加）
      // proxy: {
      //   '/api': {
      //     target: 'http://your-api-server',
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(/^\/api/, '')
      //   }
      // }
    },
  }
})